package com.coolcard.framework.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.ProblemDetail;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 全局异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 500 非受控异常
    @ExceptionHandler(Exception.class) // 定义处理哪类异常
    public ProblemDetail exception(Exception e) {
        log.error("未知异常", e);
        return new CustomProblemDetail(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }


    // 501 自定义异常
    @ExceptionHandler(CustomException.class)
    public ProblemDetail serverExceptionHandler(CustomException e) {
        return new CustomProblemDetail(e.getErrorCode(), e.getMessage());
    }


    // 400 请求参数校验异常
    @ExceptionHandler(HandlerMethodValidationException.class)
    public ProblemDetail methodArgumentNotValidExceptionHandler(HandlerMethodValidationException e) {
        String resultMessage = e.getAllErrors().stream().map(error -> {
            DefaultMessageSourceResolvable defaultMessageSourceResolvable = (DefaultMessageSourceResolvable) Objects.requireNonNull(error.getArguments())[0];
            String fieldName = defaultMessageSourceResolvable.getDefaultMessage();
            return fieldName + error.getDefaultMessage();
        }).collect(Collectors.joining("；"));

        return new CustomProblemDetail(ErrorCode.VALIDATE_FAILED, resultMessage);
    }


    // 404 访问的资源不存在异常
    @ExceptionHandler(NoResourceFoundException.class)
    public ProblemDetail noHandlerFoundExceptionHandler(NoResourceFoundException e) {
        return new CustomProblemDetail(ErrorCode.NOT_FOUND, e.getMessage());
    }

    // 4041 无指定数据异常
    @ExceptionHandler(NoSuchElementException.class)
    public ProblemDetail noHandlerFoundExceptionHandler(NoSuchElementException e) {
        return new CustomProblemDetail(ErrorCode.No_Such_Element, e.getMessage());
    }


    // 405 请求方法不支持异常
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ProblemDetail noHandlerFoundExceptionHandler(HttpRequestMethodNotSupportedException e) {
        return new CustomProblemDetail(ErrorCode.METHOD_NOT_ALLOWED, e.getMessage());
    }
}
